package com.hy.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 *
 *
 * @Description: 脏话过滤器
 * @Author: zhangzhengwei2006
 * @Date: 2024-01-08 10:40
 *
 *
 */
@WebFilter(value = "/*", filterName = "BadLanguageFilter")
public class BadLanguageFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("BadLanguageFilter============>");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String ac = req.getParameter("ac");
        DirtyWordsHttpServletRequest dirtyRequest = new DirtyWordsHttpServletRequest(req);

        if (!"register".equals(ac)){
            chain.doFilter(dirtyRequest, resp);
            return;
        }

        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

    }

    private class DirtyWordsHttpServletRequest extends HttpServletRequestWrapper {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("BadLanguage.txt");
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        //        private String[] dirtyWords = null;

        List<String> dirtyWords = new ArrayList<String>();

        public DirtyWordsHttpServletRequest(HttpServletRequest request) {
            super(request);
        }

        @Override
        public String getParameter(String name) {
            String value = super.getParameter(name);
            if (value == null) return null;
            try {
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    dirtyWords.add(line);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            for (String dword : dirtyWords) {
                for (String s : dword.split(",")) {
                    if (value.contains(s)) {
                        value = value.replace(s, "**");
                    }
                }
            }
            return value;
        }
    }
}
